package com.android.accessibility.function;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import android.accessibilityservice.AccessibilityService;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.android.accessibility.utils.Log;

public class AutoClicklikeAccessibility extends Accessibility {

    private static final boolean ALLOW_CLICK = true;
    private static final CharSequence CircleFriendsUI = "com.tencent.mm.plugin.sns.ui.SnsTimeLineUI";
    private Queue<Item> mItemList;
    private List<Item> mClickedList = null;
    private static boolean sIsScrolling = false;

    public AutoClicklikeAccessibility(AccessibilityService service) {
        super(service);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int eventType = event.getEventType();
        Log.d(Log.TAG, "mClassName : " + mClassName);
        if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            if (CircleFriendsUI.equals(mClassName)) {
                Log.d(Log.TAG, "AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED");
                init();
                sleep(500);
                performClick();
            }
        } else if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
            if (CircleFriendsUI.equals(mClassName)) {
                Log.d(Log.TAG, "AccessibilityEvent.TYPE_VIEW_SCROLLED");
                sIsScrolling = false;
                fillList();
                sleep(500);
                performClick();
            }
        } else if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
            if (CircleFriendsUI.equals(mClassName)) {
                Log.d(Log.TAG, "AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED");
                sleep(500);
                performClick();
            }
        }
    }

    private void init() {
        if (mItemList == null) {
            mItemList = new LinkedBlockingQueue<Item>();
            mClickedList = new ArrayList<AutoClicklikeAccessibility.Item>();
        }
        fillList();
    }

    private void clean() {
        mItemList = null;
    }

    private void fillList() {
        List<Item> list = getListItem();
        addAll(list);
    }

    private void addAll(List<Item> list) {
        if (mItemList == null || list == null) {
            return;
        }
        for (Item i : list) {
            mItemList.add(i);
        }
    }

    private boolean isContain(Item item) {
        if (mClickedList == null) {
            return false;
        }
        for (Item i : mClickedList) {
            if (i.id != null && i.id.equals(item.id)) {
                return true;
            }
        }
        return false;
    }

    private void performClick() {
        if (!ALLOW_CLICK) {
            return;
        }
        if (mItemList == null) {
            return;
        }
        if (mItemList.size() > 0) {
            Item nodeInfo = mItemList.poll();
            if (nodeInfo != null) {
                ClipboardManager clipboard = (ClipboardManager) getService()
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("label", "aaaaaa");
                clipboard.setPrimaryClip(clip);
                if (nodeInfo.commentInfo != null) {
                    Log.d(Log.TAG, "nick : " + nodeInfo.nickName);
                    nodeInfo.commentInfo
                            .performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    sleep(1000);
                    Helper.findAndPerformAction(getService(), "赞");
                    mClickedList.add(nodeInfo);
                }
            }
        } else {
            checkScroll();
        }
    }

    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void checkScroll() {
        if (mItemList != null && mItemList.size() <= 0) {
            AccessibilityNodeInfo listNodeInfo = Helper.findViewNodeInfo(
                    getService().getRootInActiveWindow(),
                    "android.widget.ListView");
            if (listNodeInfo != null && !sIsScrolling) {
                Log.d(Log.TAG, "================================================AccessibilityNodeInfo.ACTION_SCROLL_FORWARD");
                sIsScrolling = true;
                listNodeInfo
                        .performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
            }
        }
    }

    private List<Item> getListItem() {
        AccessibilityNodeInfo nodeInfo = Helper.findViewNodeInfo(getService()
                .getRootInActiveWindow(), "android.widget.ListView");
        List<Item> list = null;
        if (nodeInfo != null) {
            int count = nodeInfo.getChildCount();
            AccessibilityNodeInfo info = null;
            list = new ArrayList<Item>();
            for (int index = 0; index < count; index++) {
                info = nodeInfo.getChild(index);
                if (info.getClassName().equals("android.widget.FrameLayout")) {
                    Item item = findChild(info);
                    if (item != null) {
                        list.add(item);
                    }
                }
            }
        }
        return list;
    }

    private Item findChild(AccessibilityNodeInfo info) {
        if (info == null) {
            return null;
        }
        int count = info.getChildCount();
        AccessibilityNodeInfo childInfo;
        Item item = null;
        if (count > 0) {
            item = new Item();
            for (int index = 0; index < count; index++) {
                childInfo = info.getChild(index);
                if (item.nickName == null) {
                    if ("android.widget.TextView".equals(childInfo
                            .getClassName())) {
                        item.nickName = childInfo.getText();
                    }
                }
                if (item.commentInfo == null) {
                    if ("android.widget.ImageView".equals(childInfo
                            .getClassName())) {
                        item.commentInfo = childInfo;
                    }
                }
                item.id = String.valueOf(info.hashCode());
            }
        }
        if (item != null && item.commentInfo != null) {
            return item;
        }
        return null;
    }

    class Item {
        public CharSequence id;
        public CharSequence nickName;
        public AccessibilityNodeInfo commentInfo;

        @Override
        public String toString() {
            String out = "";
            out += "id       : " + id + "\n";
            out += "nickName : " + nickName + "\n";
            return out;
        }
    }

    @Override
    public void start() {
        init();
        sleep(500);
        performClick();
    }

    @Override
    public void stop() {
        clean();
    }
}
